import ffi from 'ffi-napi'
import ref from 'ref-napi'
import iconv from 'iconv-lite';

function paddingZero (str, len) {
  let j = str.length
  for (let i = 0; i < len - j; i++) {
    str += '\0';
  }
  return str
}
function noPassByName (str) {
  if (null != str && str != undefined) {
    if (str.length == 2) {
      return str.substring(0, 1) + '*' //截取name 字符串截取第一个字符，
    } else if (str.length == 3) {
      return str.substring(0, 1) + "*" + str.substring(2, 3)//截取第一个和第三个字符
    } else if (str.length > 3) {
      return str.substring(0, 1) + "*" + '*' + str.substring(3, str.length)//截取第一个和大于第4个字符
    }
  } else {
    return "";
  }
}
let readIcFlag = true

export default {
  init32Dll () {
    console.log('=====init win32 dll=====')
    // WriteCard(com, mode, block, chData)
    let proxy_dll = ffi.Library(`${process.env.libPath}/ia32/yict-gsa-proxy.dll`, {
      // 'ForceReconnect': ['int', []], 直接传递空数组报错
      "WriteCard": ['int', ['int', 'string', 'string']],
      "ReadCard": ['int', ['int', 'string', ref.refType(ref.types.int), 'string', ref.refType(ref.types.int)]],
      "GetIDCardInfo": ['int', ['int', 'string', ref.refType(ref.types.int), 'string', ref.refType(ref.types.int)]],
      'GetICCardInfo': ['int', ['int', 'string', ref.refType(ref.types.int), 'string', ref.refType(ref.types.int)]]
    })

    return proxy_dll
  },
  writeCard (proxy_dll, com, p8, p9) {
    const result = {
      readCode: 0,
      desc: '',
      port: com
    }
    if (p8.length > 16 || p9.length > 16) {
      result.readCode = -500
      result.desc = '写卡长度不能超过16'
      return result
    }
    if (p8.length < 16) {
      p8 = paddingZero(p8, 16)
    }
    if (p9.length < 16) {
      p9 = paddingZero(p9, 16)
    }

    for (let index = 0; index < 3; index++) {
      result.readCode = proxy_dll.WriteCard(com, Buffer.from(p8), Buffer.from(p9))
      if (result.readCode !== -401) {
        return result
      }
    }
    return result
  },
  readCard (proxy_dll, com) {
    let _p8 = Buffer.alloc(16);
    let _p9 = Buffer.alloc(16);
    let _p8_len = ref.alloc(ref.types.int);
    let _p9_len = ref.alloc(ref.types.int);

    let res = 0
    for (let index = 0; index < 3; index++) {
      res = proxy_dll.ReadCard(com, _p8, _p8_len, _p9, _p9_len)

      if (res !== -401) {
        break
      }
    }

    let p8 = ''
    let p9 = ''

    if (res === 1) {
      p8 = iconv.decode(_p8.slice(0, ref.deref(_p8_len) - 1), 'gbk')
      p9 = iconv.decode(_p9.slice(0, ref.deref(_p9_len) - 1), 'gbk')
    }
    return {
      p8: p8,
      p9: p9,
      port: com,
      readCode: res
    }
  },
  // 初始化地磅终端
  init32MeterInterfaceDll () {
    console.log('=====init32MeterInterfaceDll dll=====')

    let proxy_dll = ffi.Library(`${process.env.libPath}/ia32/MeterInterface.dll`, {
      "GetGrossWeight": ['int', ['string', ref.refType(ref.types.char)]],
      "TestDllFun": ['int', ['int', 'string', ref.refType(ref.types.char)]]
    })

    return proxy_dll
  },
  // 开始称重
  readWeightBridge (proxy_dll, type) {
    let params = JSON.stringify({
      inf_type: type,
      com_number: 'com2',
      cmd_type: '1',
      baudrate: 9600,
      log: 1
    });
    let res = Buffer.alloc(100);
    proxy_dll.GetGrossWeight(params, res)
    return iconv.decode(res, 'gbk')
  },
  resetWeightBridge (proxy_dll, type) {
    let params = JSON.stringify({
      inf_type: type,
      com_number: 'com2',
      cmd_type: '0',
      baudrate: 9600,
      log: 1
    });
    let res = Buffer.alloc(100);
    proxy_dll.GetGrossWeight(params, res)
    return iconv.decode(res, 'gbk')
  },
  readerIDCardInfo (proxy_dll) {
    let readResult = {
      readCode: 0,
      name: '',
      idNo: ''
    }

    let _name = Buffer.alloc(20);
    let _idcode = Buffer.alloc(20);
    let _name_len = ref.alloc(ref.types.int);
    let _idcode_len = ref.alloc(ref.types.int);
    //  let isReaded = true

    readResult.readCode = proxy_dll.GetIDCardInfo(1001, _name, _name_len, _idcode, _idcode_len);
    // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码
    readResult.name = iconv.decode(_name.slice(0, ref.deref(_name_len) - 1), 'gbk')
    readResult.idNo = iconv.decode(_idcode.slice(0, ref.deref(_idcode_len) - 1), 'gbk')

    readResult.saltIdNo = readResult.idNo.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2")
    readResult.saltName = noPassByName(readResult.name)
    return readResult
  },
  readerICCardInfo (port, proxy_dll) {

    let readResult = {
      readCode: 0,
      cardNo: '', //卡号
      permitNo: '', //许可证
      port: port
    }

    // 防止频繁读卡造成的资源卡顿
    if (!readIcFlag) {
      return readResult
    }

    readIcFlag = false
    let _cardNo = Buffer.alloc(16) //Buffer
    let _permitNo = Buffer.alloc(16) //Buffer
    let _cardNo_len = ref.alloc(ref.types.int) //ref.types.int
    let _permitNo_len = ref.alloc(ref.types.int) //ref.types.int

    readResult.readCode = proxy_dll.GetICCardInfo(port, _cardNo, _cardNo_len, _permitNo, _permitNo_len)

    readResult.cardNo = _cardNo.slice(0, ref.deref(_cardNo_len)).toString()
    readResult.permitNo = _permitNo.slice(0, ref.deref(_permitNo_len)).toString()
    readIcFlag = true
    //如有有中文用这样的方式
    // readResult.name = iconv.decode(_name.slice(0, ref.deref(_name_len) - 1), 'gbk')
    // readResult.idNo = iconv.decode(_idcode.slice(0, ref.deref(_idcode_len) - 1), 'gbk')
    return readResult
  }

}